package com.kuang.myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/*这个类是把源码复制过来,想在原作者的基础上,指定自己的负载均衡规则*/
/*每个服务访问5次,换下一个服务
 * 设置一个变量,初始等于0,调用一次就自增1,直到5就换下一个*/
public class KuangRandomRule extends AbstractLoadBalancerRule {
    private int total = 0; //被调用的次数
    private int currentIndex = 0; //当前是谁在提供服务

    public KuangRandomRule() {
    }

    // @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while (server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                List<Server> upList = lb.getReachableServers(); // 获得活着的服务
                List<Server> allList = lb.getAllServers(); // 获得全部服务
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }

//                int index = this.chooseRandomInt(serverCount); // 生成区间随机数
//                server = (Server) upList.get(index);  // 从活着的服务随机取出一个

                // 以下是狂神自定的负载均衡算法,用箭头标注范围
                //↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
                if (total<5){ // 一个服务调用不满5次,就一直调用本服务
                    server = upList.get(currentIndex);
                    total++;
                }else { // 调用满5次了,换下一个服务
                    total = 0;
                    currentIndex++;
                    if (currentIndex>=upList.size()){  // 服务用完一循环了,在从头开始新的循环
                        currentIndex = 0;
                    }
                   server =  upList.get(currentIndex);
                }
                //↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
